import { defineStore } from "pinia";
import { storageLocal } from "@pureadmin/utils";
import {
  userLogoutApi,
  getUserInfoApi,
  refreshUserTokenApi,
  type UserAuthData
} from "@/api/user-auth";

// 用户认证数据类型
export interface UserAuthState {
  /** 用户ID */
  userId: number | null;
  /** 用户名 */
  userName: string;
  /** 用户昵称 */
  nickName: string;
  /** 头像URL */
  avatar: string;
  /** 角色列表 */
  roles: string[];
  /** 权限列表 */
  permissions: string[];
  /** JWT令牌 */
  token: string;
  /** Token过期时间 */
  expireTime: number;
  /** 是否记住登录状态 */
  isRemembered: boolean;
}

// 存储键名
const USER_AUTH_KEY = "user-auth-info";
const USER_TOKEN_KEY = "user-auth-token";

export const useUserAuthStore = defineStore("user-auth", {
  state: (): UserAuthState => {
    // 先尝试从localStorage读取（记住登录状态的情况）
    let savedData = storageLocal().getItem<UserAuthState>(USER_AUTH_KEY);

    // 如果localStorage中没有，再尝试从sessionStorage读取（不记住登录状态的情况）
    if (!savedData) {
      try {
        const sessionData = sessionStorage.getItem(USER_AUTH_KEY);
        if (sessionData) {
          savedData = JSON.parse(sessionData);
        }
      } catch (error) {
        console.error("解析sessionStorage中的用户数据失败:", error);
      }
    }

    return {
      userId: savedData?.userId || null,
      userName: savedData?.userName || "",
      nickName: savedData?.nickName || "",
      avatar: savedData?.avatar || "",
      roles: savedData?.roles || [],
      permissions: savedData?.permissions || [],
      token: savedData?.token || "",
      expireTime: savedData?.expireTime || 0,
      isRemembered: savedData?.isRemembered || false
    };
  },

  getters: {
    /** 是否已登录 */
    isLoggedIn: state => {
      return !!state.token && state.expireTime > Math.floor(Date.now() / 1000);
    },

    /** 是否有指定角色 */
    hasRole: state => {
      return (role: string) => state.roles.includes(role);
    },

    /** 是否有指定权限 */
    hasPermission: state => {
      return (permission: string) => state.permissions.includes(permission);
    },

    /** Token是否即将过期 */
    isTokenExpiringSoon: state => {
      const now = Math.floor(Date.now() / 1000);
      const threshold = 30 * 60; // 30分钟
      return state.expireTime - now <= threshold;
    },

    /** 获取用户显示名称 */
    displayName: state => {
      return state.nickName || state.userName || "未知用户";
    }
  },

  actions: {
    /** 设置用户信息 */
    async setUserInfo(userData: UserAuthData, remember: boolean = false) {
      this.userId = userData.userId;
      this.userName = userData.userName;
      this.nickName = userData.nickName;
      this.avatar = userData.avatar || "";
      this.roles = userData.roles || [];
      this.permissions = userData.permissions || [];
      this.token = userData.token;

      // 处理expireTime：如果是相对时间（小于当前时间戳），则转换为绝对时间戳
      const currentTimestamp = Math.floor(Date.now() / 1000);
      if (userData.expireTime < currentTimestamp) {
        // 后端返回的是相对时间（秒数），转换为绝对时间戳
        this.expireTime = currentTimestamp + userData.expireTime;
      } else {
        // 后端返回的已经是绝对时间戳
        this.expireTime = userData.expireTime;
      }

      this.isRemembered = remember;

      // 保存到本地存储
      this.saveToStorage();

      // 设置Token到HTTP请求头
      this.setAuthToken(userData.token);
    },

    /** 清除用户信息 */
    clearUserInfo() {
      this.userId = null;
      this.userName = "";
      this.nickName = "";
      this.avatar = "";
      this.roles = [];
      this.permissions = [];
      this.token = "";
      this.expireTime = 0;
      this.isRemembered = false;

      // 清除本地存储（localStorage和sessionStorage）
      storageLocal().removeItem(USER_AUTH_KEY);
      storageLocal().removeItem(USER_TOKEN_KEY);
      sessionStorage.removeItem(USER_AUTH_KEY);
      sessionStorage.removeItem(USER_TOKEN_KEY);

      // 清除HTTP请求头中的Token
      this.removeAuthToken();
    },

    /** 保存到本地存储 */
    saveToStorage() {
      const data: UserAuthState = {
        userId: this.userId,
        userName: this.userName,
        nickName: this.nickName,
        avatar: this.avatar,
        roles: this.roles,
        permissions: this.permissions,
        token: this.token,
        expireTime: this.expireTime,
        isRemembered: this.isRemembered
      };

      if (this.isRemembered) {
        // 记住登录状态，保存到localStorage
        storageLocal().setItem(USER_AUTH_KEY, data);
        storageLocal().setItem(USER_TOKEN_KEY, this.token);
      } else {
        // 不记住登录状态，只在会话期间有效
        sessionStorage.setItem(USER_AUTH_KEY, JSON.stringify(data));
        sessionStorage.setItem(USER_TOKEN_KEY, this.token);
      }
    },

    /** 设置认证Token到HTTP请求头 */
    setAuthToken(token: string) {
      // Token会在HTTP拦截器中自动处理，这里不需要额外操作
      // HTTP拦截器会根据请求URL判断是否为用户端接口，并自动添加对应的token
      console.log("用户端Token已设置:", token ? "***" + token.slice(-6) : "无");
    },

    /** 移除认证Token */
    removeAuthToken() {
      // Token移除会在clearUserInfo中处理，这里不需要额外操作
      console.log("用户端Token已移除");
    },

    /** 刷新用户信息 */
    async refreshUserInfo() {
      try {
        const response = await getUserInfoApi();
        if (response.code === 200 && response.data) {
          await this.setUserInfo(response.data, this.isRemembered);
          return true;
        }
        return false;
      } catch (error) {
        console.error("刷新用户信息失败:", error);
        return false;
      }
    },

    /** 刷新Token */
    async refreshToken() {
      try {
        const response = await refreshUserTokenApi();
        if (response.code === 200 && response.data) {
          await this.setUserInfo(response.data, this.isRemembered);
          return true;
        }
        return false;
      } catch (error) {
        console.error("刷新Token失败:", error);
        return false;
      }
    },

    /** 前端登出（不调用接口） */
    logOut() {
      console.log("🔄 UserAuth Store: 执行前端登出...");
      this.clearUserInfo();

      // 触发全局登出事件，通知其他组件（如WebSocket服务）
      window.dispatchEvent(new CustomEvent("user-logout"));

      console.log("✅ UserAuth Store: 前端登出完成");
    },

    /** 用户注销 */
    async logout() {
      console.log("🔄 UserAuth Store: 开始执行logout...");

      return new Promise<void>(resolve => {
        userLogoutApi()
          .then(response => {
            console.log("✅ UserAuth Store: 注销API调用成功", response);
            if (response?.code === 200) {
              // 清除本地状态
              this.logOut();
            } else {
              console.warn(
                "⚠️ UserAuth Store: 注销API返回非200状态，仍执行前端登出"
              );
              this.logOut();
            }
            resolve();
          })
          .catch(error => {
            console.error("❌ UserAuth Store: 注销API调用失败:", error);
            // 即使后端接口失败，也执行前端注销
            this.logOut();
            resolve(); // 注意这里用resolve而不是reject，确保前端能正常处理
          });
      });
    },

    /** 检查并自动刷新Token */
    async checkAndRefreshToken() {
      if (!this.isLoggedIn) {
        return false;
      }

      if (this.isTokenExpiringSoon) {
        return await this.refreshToken();
      }

      return true;
    },

    /** 更新用户头像 */
    updateAvatar(avatar: string) {
      this.avatar = avatar;
      this.saveToStorage();
    },

    /** 更新用户昵称 */
    updateNickName(nickName: string) {
      this.nickName = nickName;
      this.saveToStorage();
    }
  }
});

// 创建store hook
export const useUserAuthStoreHook = () => {
  return useUserAuthStore();
};
